<template>
	<!-- 实名认证-表单页 -->
	<view class="real-name-form">
		<view class="content-wrapper">

			<view class="form-wrapper">
				<view class="real_tip" v-if="submitShow && !authorizationFlag">
					<view class="real-tip-image">
						<image src="/static/icon/real_2.png" mode=""></image>
					</view>
					<view class="">
						已认证
					</view>
				</view>
				<view class="real_tip" v-else>
					<view class="real-tip-image">
						<image src="/static/icon/real_1.png" mode=""></image>
					</view>
					<view class="">
						为了您的账号安全，请先进行实名认证
					</view>
				</view>
				<view class="form-item">
					<!-- 身份证件 -->
					<view class="card-wrapper">
						<view class="card-item front">
							<!-- 上传按钮 -->
							<view class="btn-upload" @click="uploadIdCardFront('idCardFront')">
								<view v-if="!formData.idCardFront">
									<image class="img" src="/static/icon/pic_add_icon.png">
									</image>
									<!-- <view class="txt">点击上传人像面</view> -->
								</view>

								<!-- 提示：点击修改 -->
								<view class="text-tips-modify" v-if="formData.idCardFront && authorizationFlag">
									点击修改
								</view>
							</view>
							<!-- 上传后的图片 -->
							<image class="uploaded-img" mode="aspectFill" :src="formData.idCardFront ||
								'/static/icon/id_card_1.png'
								">
							</image>

							<view class="txt-tips">
								身份证人像面
							</view>
						</view>
						<view class="card-item back">
							<!-- 上传按钮 -->
							<view class="btn-upload" @click="uploadIdCardBack('idCardBack')">
								<template v-if="!formData.idCardBack">
									<image class="img" src="/static/icon/pic_add_icon.png">
									</image>
									<!-- <view class="txt">点击上传国徽面</view> -->
								</template>

								<!-- 提示：点击修改 -->
								<view class="text-tips-modify" v-if="formData.idCardBack && authorizationFlag">
									点击修改
								</view>
							</view>
							<!-- 上传后的图片 -->
							<image class="uploaded-img" mode="aspectFill" :src="formData.idCardBack ||
								'/static/icon/id_card_2.png'
								">
							</image>

							<view class="txt-tips">
								身份证国徽面
							</view>
						</view>
					</view>

					<!-- 姓名 -->
					<view class="label-wrapper">
						<view class="label">
							<text class="check">*</text>
							姓名
						</view>
						<view class="value">
							<input class="input" v-model="formData.name" placeholder="自动识别姓名"
								:placeholder-style="placeholderStyle" :maxlength="15" />
						</view>
					</view>

					<!-- 身份证号 -->
					<view class="label-wrapper">
						<view class="label">
							<text class="check">*</text>
							身份证号
						</view>
						<view class="value">
							<input class="input" v-model="formData.idCardNo" type="idcard" placeholder="自动识别身份证号"
								:placeholder-style="placeholderStyle" :maxlength="18" />
						</view>
					</view>
					<!-- 身份证有效期起始 -->
					<view class="label-wrapper">
						<view class="label">
							<text class="check">*</text>
							身份证有效期起始
						</view>
						<view class="value">
							<input class="input" v-model="formData.idCardBegin" type="idcard" placeholder="自动识别身份证有效期起始"
								:placeholder-style="placeholderStyle" :maxlength="18" />
						</view>
					</view>
					<!-- 身份证有效期截止 -->
					<view class="label-wrapper">
						<view class="label">
							<text class="check">*</text>
							身份证有效期截止
						</view>
						<view class="value">
							<input class="input" v-model="formData.idCardEnd" type="idcard" placeholder="自动识别身份证有效期截止"
								:placeholder-style="placeholderStyle" :maxlength="18" />
						</view>
					</view>
				</view>
				<!-- 创建代理：按钮 -->
				<!-- 已实名 -->
				<view class="" v-if="submitShow && !authorizationFlag"></view>
				<view class="btn-submit" @click="submitEv" v-else-if="submitShow && authorizationFlag">确认提交</view>
				<view class="btn-list" v-else>
					<view class="btn-base w200 gray" @click="childUpBtn()">上一步</view>
					<view class="btn-base w470 blue" @click="childNextBtn()">下一步</view>
				</view>
			</view>
		</view>


	</view>
</template>

<script setup>
	import {
		onLoad
	} from '@dcloudio/uni-app';
	import {
		ref,
		defineEmits
	} from 'vue';
	import {
		useStore
	} from '@/store/index';
	import {
		showToast
	} from '@/utils/toast';
	import check from '@/utils/check';
	import {
		onlyCnReg,
		limitCardNoReg
	} from '@/utils/regExp';
	import {
		uploadImg,
		getOsssSignature
	} from '@/utils/upload';
	import {
		queryIdCardInfo
	} from "@/api/common";
	import {
		updateAgentSettlementInfo,
		queryAthorization
	} from '@/api/mine';
	// import {
	// 	uploadImage
	// } from '@/api/upload';

	const props = defineProps({
		submitShow: Boolean
	});
	/** store实例 */
	const store = useStore();
	// 定义要触发的事件
	const emit = defineEmits(['upBtn', 'nextBtn']);
	// oss签名配置
	let ossConfig = {};
	// 输入框提示语样式
	const placeholderStyle = 'color: #999999';

	// 表单数据
	let formData = ref({
		userId: store.userInfo.userId,
		name: '', // 身份证姓名
		idCardFront: '', // 证件照正面(人像)
		idCardBack: '', // 证件照反面
		idCardBegin: '', // 有效期-开始
		idCardEnd: '', // 有效期-结束
		idCardNo: '', // 身份证号
		idAddress: '',
		gender: '',
		birthday: '',
		issue: '',
		nationality: "",
		longTermIdCard: false,
		phone: store.userInfo.phone,
		oemUserNo: 'BU100002',

	});
	// 是否已经实名认证状态
	let authorizationFlag = ref(null)
	/** 生命周期 */
	onLoad(async (val) => {
		console.log("val888", val)
		if (val && val.authorizationFlag) {
			// oss签名配置
			// ossConfig = await getOsssSignature('agent');
			authorizationFlag.value = true
		} else {
			authorization()
			authorizationFlag.value = false
		}


	});
	// 身份证姓名
	function handleIdName(ev) {
		setTimeout(() => {
			formData.value.name = onlyCnReg(ev.detail.value);
		}, 0);
	}

	// 身份证号
	function handleNo(ev) {
		setTimeout(() => {
			formData.value.idCardNo = limitCardNoReg(ev.detail.value);
		}, 0);
	}

	// 上传人像面
	function uploadIdCardFront(sourceType) {

		if (!authorizationFlag.value) {
			return false
		}
		uploadImg(ossConfig, sourceType).then((res) => {
			let imgUrl = res;
			console.log("imgUrl", imgUrl)

			queryIdCardInfo({
				image: imgUrl,
				side: 'face',
				oemUserNo: 'BU100002'
			}).then((cardInfoRes) => {
				console.log('idCardFrontRes==>', cardInfoRes);
				formData.value.idCardFront = imgUrl;
				formData.value.name = cardInfoRes.name;
				formData.value.idCardNo = cardInfoRes.no;
				formData.value.idAddress = cardInfoRes.address;
				formData.value.gender = cardInfoRes.gender;
				formData.value.birthday = cardInfoRes.birthday;
			});
		});
	}
	// 上传国徽面
	function uploadIdCardBack(sourceType) {
		if (!authorizationFlag.value) {
			return false
		}
		uploadImg(ossConfig, sourceType).then((res) => {
			let imgUrl = res;

			queryIdCardInfo({
				image: imgUrl,
				side: 'back',
				oemUserNo: 'BU100002'
			}).then((cardInfoRes) => {
				console.log('idCardBackRes==>', cardInfoRes);

				formData.value.idCardBack = imgUrl;
				formData.value.idCardBegin = cardInfoRes.startDate;
				formData.value.idCardEnd = cardInfoRes.endDate;
				formData.value.issue = cardInfoRes.issue;
			});
		});
	}


	// 校验表单
	function verifyForm() {

		// 证件照正面(人像)
		if (!formData.value.idCardFront) {
			showToast('请上传人像面', 'none', 3000);
			return false;
		}
		// 证件照反面
		if (!formData.value.idCardBack) {
			showToast('请上传国徽面', 'none', 3000);
			return false;
		}
		// 身份证姓名
		if (!formData.value.name) {
			showToast('自动识别姓名', 'none', 3000);
			return false;
		}
		// 身份证号
		if (!formData.value.idCardNo) {
			showToast('自动识别身份证号', 'none', 3000);
			return false;
		}
		if (!check.isIdCardNo(formData.value.idCardNo)) {
			showToast('身份证号格式不对', 'none', 3000);
			return false;
		}
		return true;
	}
	// 提交
	function submitEv() {
		if (!verifyForm()) {
			return false;
		}
		let params = JSON.parse(JSON.stringify(formData.value));
		updateAgentSettlementInfo(params).then((res) => {
			console.log('提交成功=>', res);
			showToast('提交成功', 'none');
			// 返回上一层
			setTimeout(() => {
				uni.navigateBack();
			}, 1500);
		}).catch((err) => {

		});
	}
	// 已实名获取实名信息
	function authorization() {
		queryAthorization(store.userInfo.userId).then((res) => {
				console.log("res-res", res)
				formData.value.name = res.contactName;
				formData.value.idCardNo = res.settleIdCard;
				if (res.settleIdCardPeriod) {
					let hasHyphen = res.settleIdCardPeriod.includes("~"); // 返回 true 或 false
					if (hasHyphen) {
						formData.value.idCardBegin = res.settleIdCardPeriod.split("~")[0];
						formData.value.idCardEnd = res.settleIdCardPeriod.split("~")[1];
					} else {
						formData.value.idCardBegin = res.settleIdCardPeriod
						formData.value.idCardEnd = res.settleIdCardPeriod
					}
				}
				formData.value.idCardFront = res.idCardFront.split("?")[0]
				formData.value.idCardBack = res.idCardBack.split("?")[0]
			})
			.catch((error) => {
				showToast(error.data.message || error.data.error);
			});
	}
	const childUpBtn = () => {
		console.log("formData.value", formData.value)
		emit('upBtn');
	}
	const childNextBtn = () => {
		console.log("formData.value888", formData.value)
		emit('nextBtn', formData.value, 1)
	}
</script>

<style lang='scss' scoped>
	@import './index.scss';
</style>